const {cityModel} = require('../models/city_sales')
const {provinceModel, getYear} = require('../models/province_sales')
const {countyModel} = require('../models/county_sales')
const {raw} = require("body-parser");
const zlib = require("zlib")
//操作数据库的方法（在router_handler中调用）
//点击地图查询省份数据(点击的城市以及下一级城市信息都有)
const onclick_data = (code,level) => {
    switch (level){
        case 1:
            return provinceModel.aggregate([
                {
                    $lookup:{
                        from:'city_year',
                        localField:'province_code',
                        foreignField:'province_code',
                        as:'city_info'
                    }
                },
                {
                    $match:{
                        'province_code':code
                    }
                }
            ])
                .then((res)=>{
                    for (let i = 0; i < res.length; i++) {
                        let info = res[i].city_info.filter(item=>{
                            return item.year === res[i].year
                        })
                        res[i].city_info.splice(0,res[0].city_info.length,info)
                    }

                    return res
                    // return JSON.parse(JSON.stringify(res)).sort((a,b)=>{
                    //     return a.year.slice(0,4) - b.year.slice(0,4)
                    // })
                })
                .catch((err)=>{
                    console.log(err)
                    return false
                })
        case 2:
            return cityModel.aggregate([
                {
                    $lookup:{
                        from:'county_year',
                        localField:'city_code',
                        foreignField:'city_code',
                        as:'county_info'
                    }
                },
                {
                    $match:{
                        'city_code':code
                    }
                }
            ])
                .then((res)=>{
                    for (let i = 0; i < res.length; i++) {
                        let sss = res[i].county_info.filter(item=>{
                            return item.year === res[i].year
                        })
                        res[i].county_info.splice(0,res[0].county_info.length,sss)
                    }
                    return JSON.parse(JSON.stringify(res)).sort((a,b)=>{
                        return a.year.slice(0,4) - b.year.slice(0,4)
                    })
                })
                .catch((err)=>{
                    return false
                })
        default:
            break;
    }
}

/***
 * 销售总量排行
 * @param code
 * @param level
 * @returns {Promise<*>}
 */
const getRankingOfCity = async (code,level) => {
    let rankingAllData = []
    const getInfo = (code,level,time) => {
        return (level === 1 ? cityModel : countyModel).aggregate([
            {
                $match:{
                    [level === 1 ? 'province_code':'city_code']:code,
                    year:time
                }
            },
            {
                $project:{
                    [level === 1 ? 'city' : 'county']:1,
                    year:1,
                    redPlatform:'$sales.sales_red_sum',
                    greenPlatform:'$sales.sales_green_sum',
                    otherPlatform:'$sales.sales_other_sum',
                }
            }
        ])
            .then((res)=>{
                let salesInfo = []
                for (let i = 0; i < res.length; i++) {
                    let sum = res[i].redPlatform + res[i].greenPlatform + res[i].otherPlatform
                    salesInfo.push({city:level === 1 ? res[i].city : res[i].county,sales:sum})
                }
                rankingAllData.push({year:res[0].year,
                    salesInfo:JSON.parse(JSON.stringify(salesInfo)).sort((a,b) => {
                        return b.sales - a.sales
                    })})
                return rankingAllData
            })
            .catch((err)=>{
                console.log(err)
                return false
            })
    }

    let timeData = await getYear()
    for (let i = 0; i < timeData.length; i++) {
        await getInfo(code,level,timeData[i])
    }

    return JSON.parse(JSON.stringify(rankingAllData)).sort((a,b) => {
        return a.year - b.year
    })
}

//热门平台圆饼图数据
const getProductPie = async (code,level) => {
    let classification = await onclick_data(code,level)
    //热门平台销量图表数据
    let productTotalSales = []
    classification.map(item => {
        let products = []
        let productName = []
        item.platform_classification.platform_sales.map(product => {
            let sales = Object.values(...Object.values(product))
            let sum = 0
            sales.map(values => {
                sum += +values
            })
            products.push(sum)
            productName.push(...Object.keys(product))
        })
        // let product = ['京东','淘宝','拼多多','盒马','美团']
        productTotalSales.push({year:item.year,city:item.city,products,productName})
    })
    return productTotalSales
}

/***
 * 点击地图获取龙虾分类的数据(除开全省)
 * @param code  城市的code
 * @param level 城市级别
 * @returns {*|Promise<any>}
 */
const platformClassificationOfCityData = async (code,level) => {
    let platformAllData = []
    const getInfo = (code,level,time) => {
        return (level === 1 ? cityModel : countyModel).aggregate([
            {
                $match:{
                    [level === 1 ? 'province_code':'city_code']:code,
                    year:time
                }
            },
            {
                $project:{
                    [level === 1 ? 'city' : 'county']:1,
                    year:1,
                    // sales:1,
                    redPlatform:'$sales.sales_red_sum',
                    greenPlatform:'$sales.sales_green_sum',
                    otherPlatform:'$sales.sales_other_sum',
                }
            }
        ])
            .then((res)=>{
                let city = []
                let redPlatform = []
                let greenPlatform = []
                let otherPlatform = []
                let platformSum = []
                for (let i = 0; i < res.length; i++) {
                    city.push(level === 1 ? res[i].city : res[i].county)
                    redPlatform.push(res[i].redPlatform)
                    greenPlatform.push(res[i].greenPlatform)
                    otherPlatform.push(res[i].otherPlatform)
                    let  sum = res[i].redPlatform + res[i].greenPlatform + res[i].otherPlatform
                    platformSum.push(sum)
                }
                let legendName = ["销售总量","红尾虾","绿尾虾","其他"]
                platformAllData.push({year:res[0].year,
                    city,
                    allData:[
                        platformSum,
                        redPlatform,
                        greenPlatform,
                        otherPlatform
                    ],
                    legendName
                })
                return platformAllData
            })
            .catch((err)=>{
                console.log(err)
                return false
            })
    }

    let timeData = await getYear()
    for (let i = 0; i < timeData.length; i++) {
        await getInfo(code,level,timeData[i])
    }
    return JSON.parse(JSON.stringify(platformAllData)).sort((a,b) => {
        return a.year - b.year
    })
}

const productClassificationOfCityData = async (code,level) => {
    let productAllData = []
    const getInfo = (code,level,time) => {
        return (level === 1 ? cityModel : countyModel).aggregate([
            {
                $match:{
                    [level === 1 ? 'province_code':'city_code']:code,
                    year:time
                }
            },
            {
                $project:{
                    [level === 1 ? 'city' : 'county']:1,
                    year:1,
                    platform_classification:1,
                }
            }
        ])
            .then((res)=>{
                let city = []
                let jdProduct = []
                let tbProduct = []
                let pddProduct = []
                let hmProduct = []
                let mtProduct = []
                for (let i = 0; i < res.length; i++) {
                    city.push(level === 1 ? res[i].city : res[i].county)
                    let allProductSales = []
                    let sales = res[i].platform_classification.platform_sales
                    for (let i = 0; i < sales.length; i++) {
                        let values = Object.values(...Object.values(sales[i]))
                        let sum = 0
                        values.map(value => {
                            sum += +value
                        })
                        allProductSales.push(sum)
                    }
                    jdProduct.push(allProductSales[0])
                    tbProduct.push(allProductSales[1])
                    pddProduct.push(allProductSales[2])
                    hmProduct.push(allProductSales[3])
                    mtProduct.push(allProductSales[4])
                }
                let legendName = ['京东','淘宝','拼多多','盒马','美团']
                productAllData.push({city,year:time,
                    allData:[
                        jdProduct,
                        tbProduct,
                        pddProduct,
                        hmProduct,
                        mtProduct
                    ],
                    legendName
                })
                return productAllData
            })
            .catch((err)=>{
                console.log(err)
                return false
            })
    }

    let timeData = await getYear()
    for (let i = 0; i < timeData.length; i++) {
        await getInfo(code,level,timeData[i])
    }
    return productAllData
    // return JSON.parse(JSON.stringify(productAllData)).sort((a,b) => {
    //     return a.year - b.year
    // })
}

//模糊提示全国的数据
const allCityInfo = async () => {
    const getProvinceInfo = () => {
        return provinceModel.find({},{city:1})
            .then(res => res)
            .catch(err => {
                console.log(err)
                return false
            })
    }

    const getCityInfo = () => {
        return cityModel.find({},{city:1})
            .then(res => res)
            .catch(err => {
                console.log(err)
                return false
            })
    }

    const getCountyInfo = () => {
        return countyModel.find({},{county:1})
            .then(res => res)
            .catch(err => {
                console.log(err)
                return false
            })
    }

    let provinceInfo = await getProvinceInfo()
    let cityInfo = await getCityInfo()
    let countyInfo = await getCountyInfo()

    return [...provinceInfo,...cityInfo,...countyInfo]
}

//计算模糊查询数据总条数
const allCityDataTotal = async (city) => {
    let reg = ''
    if (city !== '' || undefined) reg = new RegExp(city)
    let provinceInfo = () => {
        return provinceModel.find(city !== '' || undefined ? {'city':{$regex:reg}} : {})
            .then(res=>res)
            .catch(err => {
                console.log(err)
                return false
            })
    }

    let cityInfo = () => {
        return cityModel.find(city !== '' || undefined ? {'city':{$regex:reg}} : {})
            .then(res => res)
            .catch(err => {
                    console.log(err)
                    return false
                })
    }

    let county = () => {
        return countyModel.find(city !== '' || undefined ? {'county':{$regex:reg}} : {})
            .then(res => res)
            .catch(err => {
                console.log(err)
                return false
            })
    }

    let provinceLength = await provinceInfo()
    let cityLength = await cityInfo()
    let countyLength = await county()

    return [...provinceLength,...cityLength,...countyLength].length
}

/**
 * 城市数据分页模糊查询
 * @param city 模糊数据名
 * @param pageSize 条数
 * @param pageNo 页数
 * @returns {Promise<T | boolean>}
 */
const inquireOfCityData = async (city,pageSize,pageNo) => {
    let reg = ''
    if (city !== '' || undefined) reg = new RegExp(city)
    let skipNumber = pageSize * (pageNo-1)
    let dataLength = await allCityDataTotal(city)
    //city跳过的数据中又包含了一份province的数据，相当于在请求city时直接跳过了province所查询的数据条数
    let provinceNumber = () => {
        return provinceModel.find(city !== '' || undefined ? {'city': {$regex: reg}} : {}).exec().then(res => {
            return res.length
        })
    }
    let proNum = await provinceNumber()
    //模糊查询到的市级数量
    let cityNumber = () => {
        return cityModel.find(city !== '' || undefined ? {'city': {$regex: reg}} : {}).exec().then(res => {
            return res.length
        })
    }
    let cityNum = await cityNumber()
    return provinceModel.find(city !== '' || undefined ? {'city':{$regex:reg}} : {}).skip(skipNumber).limit(pageSize)
        .then(res => {
            if (res.length <= 0) {
                return cityModel.find(city !== '' || undefined ? {'city': {$regex: reg}} : {}).skip(skipNumber - proNum).limit(pageSize)
                    .then(res => {
                        if (res.length <= 0) {
                            return countyModel.find(city !== '' || undefined ? {'county': {$regex: reg}} : {}).skip(skipNumber - cityNum - proNum).limit(pageSize)
                                .then(res => {
                                    return {cityInfo: res, total: dataLength}
                                })
                                .catch(err => {
                                    console.log(err)
                                    return false
                                })
                        }
                        return {cityInfo: res, total: dataLength}
                    })
                    .catch(

                    )
            } else {
                return {cityInfo: res, total: dataLength}
            }
        })
        .catch(err => {
            console.log(err)
            return false
        })
}

module.exports = {
    onclick_data, getProductPie,
    platformClassificationOfCityData,
    getRankingOfCity,
    productClassificationOfCityData,
    inquireOfCityData,
    allCityInfo
}
